<& /Minimal/Elements/Header, 
    Title       => $title,
    current_tab => "/Minimal/Search.html",
&>
<& /Elements/ListActions, actions => \@results &>

% $m->comp('Elements/SearchBox');
% if($text){
% $m->out($text);
% }


<%INIT>
my $title = loc("Collective Intelligence");
$text = undef;

if($q){
    if($q =~ /^#?(\d+)$/){
        RT::Interface::Web::Redirect(RT->Config->Get('WebURL')."Minimal/Display.html?id=".$1);
    } else {
        require CIF::Client;

        my ($client,$err) = CIF::Client->new({
            host            => RT->Config->Get('CIFMinimal_APIHostname') || RT->Config->Get('WebBaseURL').'/api',
            simple_hashes   => 1,
            fields          => $fields,
            group_map       => 1,
        });
        warn $err if($err);
        last if($err);
        require CIF::WebAPI::APIKey;
        my @recs = CIF::WebAPI::APIKey->search(uuid_alias => $session{'CurrentUser'}->UserObj->EmailAddress());
        unless($recs[0] && $recs[0]->uuid()){
            # generate apikey
            require RT::CIFMinimal;
            my $id = RT::CIFMinimal::generate_apikey({ user => $session{'CurrentUser'}->UserObj(), key_description => 'generated automatically for WebUI search' });
            push(@recs,$id);
            push(@results,'default WebUI apikey '.$id->uuid().' automatically generated');
        }
        $client->{'apikey'} = $recs[0]->uuid();
        my @res;
        my @qarray = split(/,/,$q);
        @recs = undef;
        foreach(@qarray){
            my $feed = $client->GET(
                query   => $_,
                limit   => 25,
                nolog   => $nolog,
            );
            if($feed){
                @recs = @{$feed->{'feed'}->{'entry'}};
                if($#recs > -1){
                    @recs = sort { $b->{'confidence'} cmp $a->{'confidence'} } @recs;
                    $feed->{'feed'}->{'entry'} = \@recs;
                }
            }
            require CIF::Client::Plugin::Html;
            $client->{'class'}          = 'collection';
            $client->{'evenrowclass'}    = 'evenline';
            $client->{'oddrowclass'}     = 'oddline';
            my $t = CIF::Client::Plugin::Html->write_out($client,$feed,undef);
            push(@res,$t);
        }
        $text = join("\n",@res) if(@res && $#res > -1);
        $text = '<h3>No Results</h3>' if($text eq '');
    }
}
</%INIT>


<%ARGS>
$q => undef
$text => undef
@results => undef
$nolog => undef
$fields => undef
</%ARGS>
